import React from 'react'
import {connect,} from 'react-redux'
import {withRouter,} from 'react-router-dom'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout"
import './news.css'

// import {news as MockNews, carouselData,} from "../../utils/mockdata"
// import FireIcon from "../../res/images/web/shared/fire.png"
import Logo from "../../res/images/web/news/球必应@2x.png"
import LogoAdd from "../../res/images/web/news/球必应2@2x.png"

import Share from "../../res/images/web/news/link@2x.png"
import {Toast} from "antd-mobile"
import {copyToClip} from "../../utils/copy";
// import {app_name} from "../../utils/constants";
import {getDifferenceBetweenDates} from "../../utils/dateService";
import LocalStorageService from "../../utils/LocalStorageService";
import {hitReq} from "../../apis/goApis";
import {GlobalStore} from "../../context";
import {onTaskDone} from "../plan-detail/plan-detail";
import TaskDoneNotice from "../plan-detail/task-done-notice/task-done-notice";

class NewSContainer extends React.Component {
    constructor(props) {
        super(props)
        this.newsId = this.props.match.params.newsId
        this.uid = LocalStorageService.get('userid')
        this.state = {
            atTop: true,
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {
        const newsid = Number(this.newsId)
        this.props.doFetchNewsDetail({startId: newsid,})
        this.addHit()
        this.done()
    }

    componentWillUnmount() {
        this.props.doSetNewsDetailInit()
    }

    done() {
        if (this.uid) {
            onTaskDone(this.uid, 'ydzx')
                .then(data => {
                    if (data.Code === 0) {
                        this.setState({
                            taskDone: true,
                            taskInfo: data.Msg,
                        })
                    }
                })
        }
    }

    addHit = () => {
        const userid = LocalStorageService.get('userid')
        if (userid) {
            hitReq({
                userid,
                handle: 1,
            })
        }
    }

    share = () => {
        const href = window.location.href
        const copy = copyToClip(href)
        if (copy) {
            Toast.info('复制成功')
        } else {
            Toast.info('复制不成功 请手动复制')
        }
    }

    onCtnTouchEnd = () => {
        const rect = this.ctn.getBoundingClientRect()
        const top = rect.top
        // if (top )
        if (top < 45) {
            this.setState({
                atTop: false,
            })
        } else if (top === 45) {
            this.setState({
                atTop: true,
            })
        }
        // console.log(rect)
    }

    goBack = () => {
        this.context.topic.setFromNews()
        this.props.history.goBack()
    }

    render() {
        const currentNews = this.props.news.currentNews
        let {
            detailPag,
            detailImg,
        } = currentNews
        const content = []
        const pagL = detailPag.length
        detailPag = detailPag.slice(0, pagL - 1)
        const imgL = detailImg.length
        for (let i = 0; i < imgL; i++) {
            const img = detailImg[i]
            const p = detailPag[i]
            const pagObj = {
                key: 'p',
                value: p,
            }
            const imgObj = {
                key: 'img',
                value: img
            }
            content.push(imgObj, pagObj)
            if (i === imgL - 1) {
                if (imgL > pagL) {
                    const rest = detailImg.slice(i + 1)
                    let r = []
                    rest.map(n => r.push({key: 'img', value: n}))
                    content.push(...r)
                } else {
                    const rest = detailPag.slice(i + 1)
                    let r = []
                    rest.map(n => r.push({key: 'p', value: n}))
                    content.push(...r)
                }
            }
        }
        const title = (
            <div className='news-page-title'>
                <p>{currentNews.title}</p>
            </div>
        )

        // eslint-disable-next-line array-callback-return
        const contentTemplate = content.map((val, index) => {

            const {
                key,
                value
            } = val

            if (key === 'p') {
                return <p
                    key={index}
                    style={{
                        fontSize: '18px',
                        lineHeight: '30px',
                    }}
                >{value}</p>
            }
            if (key === 'img') {
                return <img
                    style={{
                        width: '100%',
                        margin: '16px 0',
                    }}
                    src={value}
                    alt=''
                    key={index}
                />
            }

        })

        // const mainTitle = (
        //     <p
        //         style={{
        //             color: '#333',
        //             fontSize: '18px',
        //             fontWeight: '900',
        //             fontFamily: '宋体',
        //         }}
        //     >有球必应</p>
        // )
        const mainLogo = <img alt='' src={Logo} style={{width: 58, height: 20,}}/>
        const mainLogoAdd = <img alt='' src={LogoAdd} style={{width: 85, height: 28,}}/>
        const mainTitle = <div className='flex-center-align-center'>
            {/*{this.state.atTop ? '' : mainLogo}*/}
            {this.state.atTop ? mainLogo : mainLogoAdd}
            {/*<p className='main-title'>{app_name}</p>*/}
        </div>
        const bottom = <div
            style={{
                marginTop: '1px',
                marginBottom: '8px',
                height: '44px',
                textAlign: 'center',
                background: '#fff',
            }}
            onClick={(e) => this.props.history.push('../newslist')}
        >
            <span style={{lineHeight: '44px', color: '#FFA500',}}>点击查看更多资讯</span>
        </div>
        const share = <div
            style={{
                width: '100%',
                height: '60px',
                background: '#fff',
            }}
            className='flex-space-around-align-center'
        >
            {/*<p>分享</p>*/}
            <div style={{textAlign: 'center',}}>
                <img src={Share} alt='' style={{height: 24, width: 24,}} onClick={this.share}/>
                <p>复制链接</p>
            </div>

        </div>

        const now = new Date()
        const creatAt = new Date(currentNews.createt * 1000)
        const minBefore = getDifferenceBetweenDates(creatAt, now).minutesDiff
        const subTitle = (
            <div className='news-page-sub-title'>
                <span className='gray-text'>{currentNews.readnum} 阅读</span>
                <span className='gray-text'>{minBefore}分钟前</span>
            </div>
        )

        return <>
            {this.state.taskDone && <TaskDoneNotice taskInfo={this.state.taskInfo} onCancel={() => this.setState({taskDone: false,})}/>}
            <GoBackLayout
                history={this.props.history}
                mainTitle={mainTitle}
                onLeftClick={() => this.goBack()}
            >
                <div

                    style={{
                        height: 'calc((100 * var(--vh) - 45px))',
                        overflow: 'auto',
                        overflowY: 'scroll',
                        // paddingBottom: '50px',

                    }}
                    onScroll={this.onCtnTouchEnd}
                >
                    <div className='news-page-ctn'
                         ref={el => this.ctn = el}
                        // onTouchEnd={this.onCtnTouchEnd}

                    >
                        <div style={{
                            background: '#fff',
                            padding: '15px'
                        }}>
                            {title}
                            {subTitle}
                            {/*{newsImage}*/}
                            {contentTemplate}
                        </div>
                        {bottom}
                    </div>
                    {share}
                </div>

            </GoBackLayout>
        </>



        // const newsImage = currentNews.imgUrl ? <img src={currentNews.imgUrl} className='news-page-image' alt=''/> : null
        // const contents = currentNews.contents !== undefined ? currentNews.contents : []
        // const newsContent = contents.map((contentItem, index) => {
        //     const [key, value,] = Object.entries(contentItem)[0]
        //
        //     if (key === 'p') {
        //         console.log('p')
        //         return <p
        //             key={index}
        //             style={{
        //                 fontSize: '16px',
        //                 lineHeight: '22px',
        //             }}
        //         >{value}</p>
        //     }
        //     if (key === 'h2') {
        //         console.log('h2')
        //         return <h2
        //             key={index}
        //             style={{
        //                 lineHeight: '2rem',
        //                 margin: '16px 0',
        //                 fontWeight: 'bold',
        //             }}
        //         >{value}</h2>
        //     }
        //     if (key === 'img') {
        //         console.log('img')
        //         return <img
        //             style={{
        //                 width: '100%',
        //                 margin: '16px 0',
        //             }}
        //             src={value}
        //             alt=''
        //             key={index}
        //         />
        //     }
        // })
        // const newsContent = (
        //     <div className='news-page-content'>
        //         <p>详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分详情内容正文部分</p>
        //     </div>
        // )



        // return <GoBackLayout
        //     history={this.props.history}
        // >
        //     <div className='news-page-ctn'>
        //         <WingBlank>
        //             {title}
        //             {subTitle}
        //             {newsImage}
        //             {newsContent}
        //             {bottom}
        //         </WingBlank>
        //     </div>
        //
        // </GoBackLayout>
    }
}


const mapState = (state) => ({
    news: state.news,
})

const mapDispatch = dispatch => ({
    doFetchNewsDetail: (payload) => dispatch.news.doFetchNewsDetail(payload),
    doSetNewsDetailInit: () => dispatch.news.doSetNewsDetailInit(),
})

NewSContainer.contextType = GlobalStore

export default connect(mapState, mapDispatch)(withRouter(NewSContainer))
